package com.xyzwps.website.modules.user;

import com.xyzwps.lib.express.HttpResponse;
import com.xyzwps.lib.express.SetCookie;
import com.xyzwps.lib.express.router.annotation.openapi.Operation;
import com.xyzwps.lib.express.router.annotation.openapi.Tags;
import com.xyzwps.lib.express.router.annotation.rest.*;
import com.xyzwps.lib.openapi.element.In;
import com.xyzwps.website.common.OK;
import com.xyzwps.website.modules.user.payload.LoginBasicPayload;
import com.xyzwps.website.modules.user.payload.SendRegisterVcodePayload;
import com.xyzwps.website.modules.user.payload.SimpleRegisterPayload;
import com.xyzwps.website.modules.user.service.SimpleAuthenticationService;
import io.avaje.validation.ValidMethod;
import jakarta.inject.Singleton;

import java.util.Map;

@Singleton
@API("/api/users")
@Tags("Users API")
public class UserApis {

    private final SimpleAuthenticationService authenticationService;

    public UserApis(SimpleAuthenticationService authenticationService) {
        this.authenticationService = authenticationService;
    }

    @ValidMethod
    @POST("/register/simple/vcode")
    @Operation(summary = "simple register: send vcode")
    public OK sendRegisterVcode(@Body SendRegisterVcodePayload payload) {
        authenticationService.sendRegisterVcode(payload.getPhone());
        return OK.INSTANCE;
    }

    @ValidMethod
    @POST("/register/simple")
    @Operation(summary = "simple register")
    public OK register(@Body SimpleRegisterPayload payload) {
        authenticationService.register(payload.getPhone(), payload.getVcode());
        return OK.INSTANCE;
    }

    @ValidMethod
    @POST("/login/simple")
    @Operation(summary = "simple login")
    public LoginBasicPayload login(
            @Body LoginBasicPayload payload, HttpResponse resp) {
        var setCookies = resp.cookies();
        setCookies.add(new SetCookie("a", "b").path("/").secure(true));
        setCookies.add(new SetCookie("c", "d").path("/").httpOnly(true));
        return payload;
    }

    @GET("/{id}")
    public Map<String, Object> getById(@RequestParam(name = "id", in = In.PATH, description = "User id") int id) {
        return Map.of("id", id);
    }

    @POST("/{id}")
    public Map<String, Object> create(@RequestParam(name = "id", in = In.PATH, description = "User id") int id) {
        return Map.of("id", id);
    }
}
